import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd/message';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {UserService} from '../user.service';
import {RoleService} from '../../role-list/role.service';

@Component({
  selector: 'user-list-edit',
  templateUrl: './user-edit.component.html',
})
export class UserEditComponent implements OnInit {


  constructor(private formBuilder: FormBuilder,
              private menService: UserService,
              private msgSrv: NzMessageService,
              private roleSrv: RoleService) {
  }

  @Output() voted = new EventEmitter();

  validateForm!: FormGroup;

  allRoleList = [];

  visible = false;
  value?: string;

  open(): void {
    this.visible = true;
  }

  edit(param) {
    this.visible = true;
    this.value = param?.parent?.id;

    if (param) {
      this.validateForm.patchValue(param);
    } else {
      this.validateForm.reset();
    }
  }

  close(): void {
    this.visible = false;
  }

  submitForm(): void {

    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if(this.validateForm.invalid){
      return;
    }

    this.menService.updateInfo(this.validateForm.value).subscribe((res) => {
      if (res.code === 1) {
        this.msgSrv.success('保存完成');
        this.close();
        this.voted.emit();
      } else {
        this.msgSrv.error(res.message);
      }
    });
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {required: true};
    } else if (control.value !== this.validateForm.controls.password.value) {
      return {confirm: true, error: true};
    }
    return {};
  };

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }


  ngOnInit(): void {
    this.validateForm = this.formBuilder.group({
      id: [null],
      username: [null, [Validators.required]],
      sex: [null, [Validators.required]],
      age: [null, [Validators.required]],
      roleIds: [],
      nickname: [null],
      phoneNum: [null],
      email: [null],
      memo: [null],
    });


    this.roleSrv.getAll().subscribe((res) => {
      if (res.code === 1) {
        this.allRoleList = res.data;
      } else {
        this.msgSrv.error(res.message);
      }
    });
  }


  onChange($event: string): void {
    console.log($event);
  }
}
